package com.business.common.utils;


import com.business.common.enums.ImageTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FileUtil {


	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(new File(filePath + fileName));
        out.write(file);
        out.flush();
        out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在
		if (file.exists()) {
			return file.delete();
		} else {
			return false;
		}
	}

    public static boolean delFolder(String folderPath) {
        try {
            deleteFiles(folderPath); //删除完里面所有内容
            File myFilePath = new File(folderPath);
            return myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除目录下所有的文件
     * @param filePath
     */
    public static boolean deleteFiles(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (filePath.endsWith(File.separator)) {
                temp = new File(filePath + tempList[i]);
            } else {
                temp = new File(filePath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
                flag = true;
            }
            if (temp.isDirectory()) {
                deleteFiles(filePath + "/" + tempList[i]);//先删除文件夹里面的文件
                deleteFiles(filePath + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
	
	/**
     * 判断路径是否存在，如果不存在则创建
     * 
     * 
     * @param dir
     */
    public static void mkdirs(String dir) {
        if (StringUtils.isEmpty(dir)) {
            return;
        }

        File file = new File(dir);
        if (file.isDirectory()) {
            return;
        } else {
            file.mkdirs();
        }
    }



    /**
     * 通过魔数判断文件类型
     * @param file
     * @return
     * @throws IOException
     */
    public static ImageTypeEnum getType(MultipartFile file) throws IOException {

        // 获取文件头
        String fileHead = getFileHeader(file);

        if (fileHead != null && fileHead.length() > 0) {
            fileHead = fileHead.toUpperCase();
            ImageTypeEnum[] fileTypes = ImageTypeEnum.values();

            for (ImageTypeEnum type : fileTypes) {
                if (fileHead.startsWith(type.getValue())) {
                    return type;
                }
            }
        }

        return null;
    }

    /**
     * 读取文件头
     * @param file
     * @return
     * @throws IOException
     */
    private static String getFileHeader(MultipartFile file) throws IOException {
        byte[] b = new byte[28];
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
            inputStream.read(b, 0, 28);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return bytesToHex(b);
    }

    /**
     * 验证上传的图片大小是否符合要求
     * @param file
     * @return
     */
    public static boolean validateFileSize(MultipartFile file,int size) {

        // 判断图片是否为空
        if (!file.isEmpty()) {
            // 若图片大于0KB且不大于15MB
            if ((file.getSize() <= 0 || file.getSize() > (size * 1024 * 1024)))
                return false;
        }

        return true;
    }

    /**
     * 将字节数组转换成16进制字符串
     *
     * @param src
     * @return
     */
    public static String bytesToHex(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     *
     * @param outputStream
     */
    public static void outByOutputStream(OutputStream outputStream,File file){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            int i = 0;
            while ((i = inputStream.read()) != -1) {
                outputStream.write(i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream !=null){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
